package com.example.springpethospital.common.service;

import com.example.springpethospital.common.exception.PetHospitalException;
import com.example.springpethospital.common.reponse.BaseResponse;
import com.example.springpethospital.common.reponse.ResponseCodeEnum;

import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 捕捉异常
 */
@ControllerAdvice
@Slf4j
public class BaseController {

    @Resource
    protected HttpSession session;
    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;

    private void exceptionWarnLogger(Exception e) {
        String httpHeaderText = this.getHttpHeaderText();
        if (request.getContentType() != null && request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            log.error("header: {} body: {}", httpHeaderText, MDC.get("requestBody"), e);
        }
    }

    /**
     * 捕获业务异常,转换为result
     */
    @ExceptionHandler({PetHospitalException.class})
    @ResponseBody
    public BaseResponse newCoreExceptionHandler(Exception ex) {
        this.exceptionWarnLogger(ex);
        return new BaseResponse(ResponseCodeEnum.FORBIDDEN, ex.getMessage());
    }

    private String getHttpHeaderText() {
        StringBuilder sb = new StringBuilder();
        sb.append(request.getMethod())
                .append(" ")
                .append(request.getRequestURI())
                .append(" ")
                .append(request.getProtocol())
                .append("\n");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(headerName);
            sb.append(headerName).append(": ");
            while (headers.hasMoreElements()) {
                sb.append(headers.nextElement());
                if (headers.hasMoreElements()) {
                    sb.append(",");
                }
            }
            if (headerNames.hasMoreElements()) {
                sb.append("\n");
            }
        }
        return sb.toString();
    }
}

